<template>
    <div class="static-website-page" v-loading="pageLoading">
        <!-- 1. 页面头部：标题和描述 -->
        <el-card shadow="never" class="page-header-card">
            <template #header>
                <div class="card-header">
                    <span>静态网站托管</span>
                </div>
            </template>
            <p class="description">
                将您的存储桶配置为一个可以公开访问的静态网站。上传您的 HTML、CSS、JavaScript 和其他静态文件后，
                即可通过对象存储（OSS）提供的访问域名直接访问您的网站。此功能非常适合托管个人博客、产品文档或前后端分离的前端应用。
            </p>
        </el-card>

        <!-- 2. 配置详情区域 -->
        <el-card shadow="never" class="config-details-card">
            <template #header>
                <div class="card-header">
                    <span>配置信息</span>
                </div>
            </template>

            <!-- 2.1 未配置状态 -->
            <div v-if="!isConfigured && !pageLoading" class="config-state not-configured">
                <el-empty description="当前未开启静态网站托管功能">
                    <el-button type="primary" :icon="Setting" @click="openDrawer">
                        立即配置
                    </el-button>
                </el-empty>
            </div>

            <!-- 2.2 已配置状态 -->
            <div v-if="isConfigured && !pageLoading" class="config-state configured">
                <el-descriptions :column="1" border>
                    <el-descriptions-item>
                        <template #label>
                            <div class="cell-item">
                                <el-icon>
                                    <DataLine />
                                </el-icon>
                                功能状态
                            </div>
                        </template>
                        <el-tag type="success" size="large">已开启</el-tag>
                    </el-descriptions-item>

                    <el-descriptions-item>
                        <template #label>
                            <div class="cell-item">
                                <el-icon>
                                    <Link />
                                </el-icon>
                                访问域名
                            </div>
                        </template>
                        <div class="access-url-wrapper">
                            <a :href="accessUrl" target="_blank" class="access-url">{{ accessUrl }}</a>
                            <el-button :icon="CopyDocument" text @click="copyToClipboard(accessUrl)">复制</el-button>
                        </div>
                    </el-descriptions-item>

                    <el-descriptions-item>
                        <template #label>
                            <div class="cell-item">
                                <el-icon>
                                    <Document />
                                </el-icon>
                                索引文档
                            </div>
                        </template>
                        <span class="config-value">{{ config.index_document }}</span>
                    </el-descriptions-item>

                    <el-descriptions-item>
                        <template #label>
                            <div class="cell-item">
                                <el-icon>
                                    <Warning />
                                </el-icon>
                                错误文档
                            </div>
                        </template>
                        <span class="config-value">{{ config.error_document || '未设置' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <div class="action-buttons">
                    <el-button type="primary" :icon="Edit" @click="openDrawer">修改配置</el-button>
                    <el-button type="danger" :icon="Delete" @click="handleDeleteConfirm">停用托管</el-button>
                </div>
            </div>
        </el-card>

        <!-- 3. 配置抽屉 (Drawer) -->
        <el-drawer v-model="drawerVisible" :title="isConfigured ? '修改静态网站托管配置' : '配置静态网站托管'" direction="rtl" size="40%">
            <el-form :model="form" ref="formRef" :rules="rules" label-position="top">
                <el-form-item label="索引文档" prop="index_document">
                    <el-input v-model="form.index_document" placeholder="例如：index.html" clearable>
                        <template #append>.html</template>
                    </el-input>
                    <div class="form-item-help">当用户访问根目录或任何子目录时，将默认展示此文件。</div>
                </el-form-item>
                <el-form-item label="错误文档 (可选)" prop="error_document">
                    <el-input v-model="form.error_document" placeholder="例如：error.html" clearable>
                        <template #append>.html</template>
                    </el-input>
                    <div class="form-item-help">当用户访问的资源不存在 (404 Not Found) 时，将展示此文件。</div>
                </el-form-item>
            </el-form>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawerVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleSave" :loading="isSubmitting">
                        {{ isSubmitting ? '正在保存...' : '确 定' }}
                    </el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive, watch } from 'vue';
import { useRoute } from 'vue-router';
import apiClient from '@/api';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Setting, Edit, Delete, Link, DataLine, Document, Warning, CopyDocument } from '@element-plus/icons-vue';
import { copyToClipboard } from '@/utils/clipboard.js';

// 1. 响应式状态定义
const route = useRoute();
const bucketName = computed(() => route.params.bucketName);

const pageLoading = ref(true);
const isConfigured = ref(false);
const config = ref({});
const drawerVisible = ref(false);
const isSubmitting = ref(false);

const form = reactive({
    index_document: '',
    error_document: '',
});
const formRef = ref(null);

const rules = reactive({
    index_document: [
        { required: true, message: '索引文档不能为空', trigger: 'blur' },
    ],
});

// 2. 计算属性
// 判断是否是开发环境
const isDev = import.meta.env.DEV;

const accessUrl = computed(() => {
    // 从 axios 实例中获取后端地址，更健壮
    const backendBaseUrl = apiClient.defaults.baseURL;
    const endpointHost = 'obs-fujian-zhihcs.cucloud.cn'; // 这个可以后续做成可配置

    if (isDev) {
        // 开发环境：使用我们创建的代理路由
        // 确保 backendBaseUrl 没有尾部斜杠
        const cleanBaseUrl = backendBaseUrl.endsWith('/') ? backendBaseUrl.slice(0, -1) : backendBaseUrl;
        return `${cleanBaseUrl}/dev-proxy/${bucketName.value}/`;
    } else {
        // 生产环境：返回真实的联通云地址
        return `http://${bucketName.value}.${endpointHost}/`;
    }
});

// 3. 方法和生命周期钩子
onMounted(() => {
    console.log('StaticWebsitePage.vue mounted!');
    if (bucketName.value) {
        console.log(`Fetching data on mount for bucket: ${bucketName.value}`);
        fetchWebsiteConfig(bucketName.value);
    } else {
        // 如果挂载时就没有bucketName，可能需要等待watch来触发
        console.warn('Mounted, but bucketName is not yet available.');
    }
});

// watch 负责处理在应用内部，路由参数 bucketName 发生变化的场景。
// (例如，如果未来有一个下拉框可以在不同 bucket 的详情页之间切换)
watch(
    bucketName,
    (newBucketName, oldBucketName) => {
        // 只有当 bucketName 真实地从一个值变成了另一个新值时，才重新加载
        if (newBucketName && newBucketName !== oldBucketName) {
            console.log(`Bucket name changed from ${oldBucketName} to ${newBucketName}, reloading...`);
            fetchWebsiteConfig(newBucketName);
        }
    }
);

// 获取配置
const fetchWebsiteConfig = async () => {
    pageLoading.value = true;
    try {
        const response = await apiClient.get(`/api/v1/buckets/${bucketName.value}/website`);
        if (response.data && response.data.index_document) {
            config.value = response.data;
            isConfigured.value = true;
        } else {
            config.value = {};
            isConfigured.value = false;
        }
    } catch (error) {
        console.error('获取静态网站配置失败:', error);
        ElMessage.error('获取配置信息失败，请重试。');
    } finally {
        pageLoading.value = false;
    }
};

// 打开抽屉
const openDrawer = () => {
    // 将当前配置填充到表单中
    form.index_document = config.value.index_document || 'index';
    form.error_document = config.value.error_document || '';
    // 移除 .html 后缀以适应 el-input 的 append
    if (form.index_document.endsWith('.html')) {
        form.index_document = form.index_document.slice(0, -5);
    }
    if (form.error_document.endsWith('.html')) {
        form.error_document = form.error_document.slice(0, -5);
    }
    drawerVisible.value = true;
};

// 保存配置
const handleSave = async () => {
    if (!formRef.value) return;
    await formRef.value.validate(async (valid) => {
        if (valid) {
            isSubmitting.value = true;
            try {
                // 自动添加 .html 后缀
                const payload = {
                    index_document: `${form.index_document}.html`,
                    error_document: form.error_document ? `${form.error_document}.html` : undefined,
                };
                await apiClient.put(`/api/v1/buckets/${bucketName.value}/website`, payload);
                ElMessage.success('静态网站托管配置已成功保存！');
                drawerVisible.value = false;
                await fetchWebsiteConfig(); // 重新获取最新配置
            } catch (error) {
                ElMessage.error('保存配置失败，请检查后端日志。');
            } finally {
                isSubmitting.value = false;
            }
        }
    });
};

// 停用确认
const handleDeleteConfirm = () => {
    ElMessageBox.confirm(
        '您确定要停用此存储桶的静态网站托管功能吗？停用后，通过访问域名将无法再访问您的网站。',
        '确认停用',
        {
            confirmButtonText: '确定停用',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        handleDelete();
    }).catch(() => {
        // 用户点击取消
    });
};

// 停用配置
const handleDelete = async () => {
    pageLoading.value = true; // 开始操作，显示加载状态
    try {
        await apiClient.delete(`/api/v1/buckets/${bucketName.value}/website`);
        ElMessage.success('静态网站托管功能已成功停用。');
        await fetchWebsiteConfig(); // 刷新状态
    } catch (error) {
        ElMessage.error('停用失败，请稍后重试。');
        pageLoading.value = false; // 出错时也要取消加载状态
    }
};

</script>

<style scoped>
.static-website-page {
    padding: 24px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 116px);
    /* 假设头部和二级导航总高116px */
}

.page-header-card,
.config-details-card {
    margin-bottom: 20px;
}

.card-header {
    font-size: 16px;
    font-weight: 500;
}

.description {
    font-size: 14px;
    color: #606266;
    line-height: 1.6;
}

.config-state {
    padding: 20px 0;
}

.not-configured {
    text-align: center;
}

.cell-item {
    display: flex;
    align-items: center;
}

.cell-item .el-icon {
    margin-right: 8px;
}

.config-value {
    font-family: 'Courier New', Courier, monospace;
    font-weight: 600;
    color: #303133;
}

.access-url-wrapper {
    display: flex;
    align-items: center;
}

.access-url {
    color: var(--el-color-primary);
    text-decoration: none;
    margin-right: 10px;
}

.access-url:hover {
    text-decoration: underline;
}

.action-buttons {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-lighter);
}

.form-item-help {
    color: #909399;
    font-size: 12px;
    line-height: 1.5;
    margin-top: 4px;
}
</style>